package com.cskaoyan.perparestatement;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PrepareStatementDemo {

    public static void main(String[] args) throws SQLException {

        // 获取连接
        Connection connection = JDBCUtils.getConnection();

        // 获取prepareStatememt对象
        // select * from user where username  = '' and password = '';
        // 这一步叫做预编译，其实就是把SQL语句先编译了，把SQL语句里面的关键字解析成命令，那么后续再去设置，设置进去的值就不会被当做sql里面的关键字来
        // 解析了，这样就解决了数据库的注入问题
        PreparedStatement preparedStatement = connection.prepareStatement("select * from user where username = ? and password = ?");

        // 设置参数
        preparedStatement.setString(1,"jingtian");
        preparedStatement.setString(2,"naicha");

        // 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            String username = resultSet.getString("username");
            int age = resultSet.getInt("age");

            System.out.println("age:" + age);

            System.out.println(username);
        }

        // 关闭资源
        JDBCUtils.closeSource(connection,preparedStatement,resultSet);


    }


}
